﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

public class RabbitMQService
{
    private readonly IConnectionFactory connectionFactory;
    private IConnection? connection;
    private IChannel? channel;

    public RabbitMQService(IConnectionFactory connectionFactory)
    {
        this.connectionFactory = connectionFactory;
    }


    public async Task InitializeAsync()
    {
        connection = await connectionFactory.CreateConnectionAsync();
        channel = await connection.CreateChannelAsync();
    }
    public async Task SendMessageAsync(string message)
    {
        //using var channel1 = await connection.CreateChannelAsync();
        await channel.QueueDeclareAsync(//申明队列
        queue: "RabbitMQQueue",//队列名字
        durable: true,          // 持久化队列
        exclusive: false,
        autoDelete: false,//是否自动删除
        arguments: null);

        await channel.ExchangeDeclareAsync(
          exchange: "RabbitMQExChange",
          type: ExchangeType.Direct, // 根据需求选择类型：Direct/Fanout/Topic/Headers
          durable: true,             // 持久化交换机
          autoDelete: false
      );
        await channel.QueueBindAsync(
            queue: "RabbitMQQueue",
            exchange: "RabbitMQExChange",
            routingKey: "RabbitMQService"
            );

        //exchange:交换机的名字，空字符指向默认交换机，
        //同时要求routingKey必须和队列名字一致，建议显式申明交换机名字

        //routingKey：路由键，决定消息保存的路径，在默认交换机下必须和队列名字一样，否则不监听。

        //body:发送的消息体 byte[]，默认无限制长度

        //可选参数：var props = channel.CreateBasicProperties();
        //props.ContentType = "application/json";  // 内容类型
        //props.ContentEncoding = "gzip";          // 压缩方式
        //props.Headers = new Dictionary<string, object>
        //{
        //    ["X-TraceID"] = Guid.NewGuid().ToString()
        //};

        //await channel.BasicPublishAsync(
        //    exchange: "",
        //    routingKey: "dotnet_queue",
        //    basicProperties: props,  // 设置消息属性
        //    body: Compress(message)  // 压缩后的消息体
        //);
        var props = new BasicProperties()
        {
            DeliveryMode = DeliveryModes.Persistent//消息持久化
        };
        await channel.BasicPublishAsync(
            exchange: "RabbitMQExChange",
            routingKey: "RabbitMQService",
            true,
            basicProperties: props,
            body: Encoding.UTF8.GetBytes(message)
            );
    }

    public async Task RecivedMessageAsync()
    {
        var consumer = new AsyncEventingBasicConsumer(channel);
        consumer.ReceivedAsync += Consumer_ReceivedAsync;
        await channel.BasicConsumeAsync(queue: "RabbitMQService", autoAck: true, consumer: consumer);
    }

    private Task Consumer_ReceivedAsync(object sender, BasicDeliverEventArgs @event)
    {
        var body = @event.Body.ToArray();
        var message = Encoding.UTF8.GetString(body);
        Console.WriteLine("Received {0}", message);
        return Task.CompletedTask;
    }


}